<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace crcl\base\mvc\response;

interface IHttp
{
}

class ContainerHttp extends Base implements IHttp
{
  //tested with external http call
  //@codeCoverageIgnoreStart
  public function flush(\crcl\base\mvc\view\IConcrete $oView)
  {
    $this->flushStatus($oView->getStatus());
    $this->flushHeaders($oView->getHeaders());
    if ($this->bExit)
    {
      exit();
    }    
    $this->flushOutput($oView->getOutput());
  }
  //@codeCoverageIgnoreEnd

  /** PRIVATE *************************************************************************************/

  private $bExit = \FALSE;

  //@codeCoverageIgnoreStart
  private function flushStatus($iStatus)
  {
    \header('HTTP/1.1 ' . $iStatus . ' ' . $this->getStatusDescription($iStatus), \TRUE, $iStatus);
    \header('Status: ' . $iStatus . ' ' . $this->getStatusDescription($iStatus));

    //when redirect, we have to exit the script
    if ($iStatus == \crcl\base\mvc\Response::STATUS_REDIRECT_PERMANENT)
    {
      $this->bExit = \TRUE;
    }
  }

  private function flushHeaders($aHeaders)
  {
    foreach ($aHeaders as $header => $value)
    {
      \header($header . ': ' . $value);
    }
  }

  private function flushOutput($sOutput)
  {
    /*eval(' ?>' . $sOutput . '<?php ');*/
    echo $sOutput;
  }

  private function getStatusDescription($iStatus)
  {
    switch ($iStatus)
    {
      case \crcl\base\mvc\Response::STATUS_OK:
        $sReturn = 'OK';
        break;
      case \crcl\base\mvc\Response::STATUS_CREATED:
        $sReturn = 'Created';
        break;
      case \crcl\base\mvc\Response::STATUS_ACCEPTED:
        $sReturn = 'Accepted';
        break;
      case \crcl\base\mvc\Response::STATUS_REDIRECT_PERMANENT:
        $sReturn = 'Moved Permanently';
        break;
      default:
        throw new Exception(
          'Unknown status',
          Exception::ERROR_HTTP_UNKNOWNSTATUS, array('status' => $iStatus));
    }
    return $sReturn;
  }
  //@codeCoverageIgnoreEnd
}
